package org.Modulo1;

import java.sql.ResultSet;
import java.util.*;
import javax.swing.JOptionPane;

public class POrMAVentas extends javax.swing.JFrame {
    //Listas con los usuarios y password de todos los empleados con acceso a la base de datos
    ArrayList<String> usuarios = new ArrayList<String>();
    ArrayList<String> password = new ArrayList<String>();

    public POrMAVentas() {
        initComponents();
        //Se conecta a la BBDD y carga los usuarios y passwords
        try {
            Agente.conectar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,"Error al cargar la BBDD: \n "+ ex.getMessage(),"Error de conexión",JOptionPane.ERROR_MESSAGE);
        }
        
        cargarLoginBBDD();
        // Hace que al pulsar el intro simule pulsar el boton Aceptar
        getRootPane().setDefaultButton(btnAceptar);
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtpassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationByPlatform(true);
        setResizable(false);

        jLabel1.setText("Usuario: ");
        jLabel1.setName(""); // NOI18N

        txtUsuario.setName("txtUsuario"); // NOI18N

        jLabel2.setText("Contraseña:");

        btnAceptar.setText("Aceptar");
        btnAceptar.setName("btnAceptar"); // NOI18N
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        jLabel3.setText("Introduzca el usuario y la contraseña:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel1))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(btnAceptar))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(txtpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnAceptar)
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*************************************************************************
     ** Comprueba que los credenciales introducidos son correctos y en caso **
     ** afirmativo cierra el formulario y abre otro para crear un pedido    **
     *************************************************************************/
    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        if(comprobarCredenciales()){
           /* AnyadirPedido a = new AnyadirPedido();
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            a.setLocationRelativeTo(this);
            a.setVisible(true);*/
            Menu m=new Menu();
            m.setVisible(true);
            this.dispose();
        }else{
            JOptionPane.showMessageDialog(null,"Usuario y/o contraseña incorrectos","Error de validación",JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnAceptarActionPerformed

    /**********************************************************
     ** Comprueba que los Usuarios y passwords instroducidos **
     ** en los JTextField coninciden con las combinaciones   **
     ** almacenadas los ArrayLIst usuarios y password        **
     **********************************************************/
    
    private boolean comprobarCredenciales(){
        int indice = -1;
        for (int i = 0; i < usuarios.size(); i++) {
            if(usuarios.get(i).equalsIgnoreCase(txtUsuario.getText()))
                indice=i;
        }
        
        String pass = new String(txtpassword.getPassword());

        if(indice != -1 && password.get(indice).equals(pass))
            return true;
        else
            return false;
    }
    
    /************************************************************************
     ** Carga los usuarios y passwords de la BBDD y los añade a las listas **
     ** usuarios y password respectivamente                                **
     ************************************************************************/
    public void cargarLoginBBDD(){
        String SQL_select = "SELECT * FROM Autentificar";
        try {
            ResultSet resultado = Agente.select(SQL_select);            
            while(resultado.next()){
                usuarios.add(resultado.getString(1));
                password.add(resultado.getString(2));
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,"Error al cargar los usuarios y contraseñas : "+ex.getMessage(),
                    "Error de conexión",JOptionPane.ERROR_MESSAGE);   
        }

       try {
            Agente.desconectar();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,"Error al desconectar la BBDD: \n "+ ex.getMessage(),"Error de conexión",JOptionPane.ERROR_MESSAGE);
        }
        
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(POrMAVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(POrMAVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(POrMAVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(POrMAVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new POrMAVentas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField txtUsuario;
    private javax.swing.JPasswordField txtpassword;
    // End of variables declaration//GEN-END:variables
}
